package com.kingyun.gpsinspection.purificationservice.services.iam.innerservice.adm.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.adm.TrainingPlanMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.TrainingPeople;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.TrainingPlan;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.IamFileService;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.adm.TrainingPeopleService;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.adm.TrainingPlanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 培训计划服务层实现层
 */

public class TrainingPlanServiceImpl implements TrainingPlanService {

    @Autowired
    private TrainingPlanMapper planMapper;
    @Autowired
    private TrainingPeopleService peopleService;
    @Autowired
    private IamFileService iamFileService;

    /**
     * 删除培训计划
     * @param trainingPlanIds
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int deleteByPrimaryKey(String[] trainingPlanIds){
        int resultCount = 0;
        if (trainingPlanIds.length>0){
            // 删除培训计划
            resultCount +=  planMapper.deleteByPrimaryKey(trainingPlanIds);
            resultCount += peopleService.deleteByTrainingPlanIds(trainingPlanIds);
        }
        return resultCount;
    }

    /**
     * 新增培训计划
     * @param record
     * @param uploadFiles 需要上传的文件
     * @param deletedFiles 需要删除的文件
     * @param empIds 培训人员id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insertSelective(TrainingPlan record,String uploadFiles,String deletedFiles,String empIds) {
        // 数据保存成功之后，返回的条数
        int resultCount = 0;
        // 判断数据是否为空
        if(null == record){
            return  resultCount;
        }
        System.out.println("》》》》jsonTree2"+record.getJsonTree());
        resultCount +=   planMapper.insertSelective(record);
        // 保存附件
        resultCount += iamFileService.newInsertFile(uploadFiles,deletedFiles,record.getTrainingId());
        TrainingPeople trainingPeople= new TrainingPeople();
        if(StringUtils.isBlank(empIds)){
            return resultCount;
        }
        // 保存培训人员
        // 培训人员数组
        String[] ids = empIds.split(",");
        // 设置创建者id
        trainingPeople.setCreatorId(record.getCreatorId());
        // 设置培训计划id
        trainingPeople.setTrainingId(record.getTrainingId());
        for(String s :ids){
            // 设置唯一id
            trainingPeople.setTrainingPeopleId(UniqueUtil.uuid());
            // 设置培训人员id
            trainingPeople.setOperatorId(s);
            // 设置创建时间
            trainingPeople.setCreateTime(new Date());
            trainingPeople.setStatus(Short.parseShort("0"));
            resultCount += peopleService.insertSelective(trainingPeople);
        }

        return  resultCount;
    }

    /**
     * 根据id查询培训计划
     * @param trainingPlanId
     * @return
     */
    @Override
    public TrainingPlan selectByPrimaryKey(String trainingPlanId) {
        if (!"".equals(trainingPlanId)){
            return  planMapper.selectByPrimaryKey(trainingPlanId);
        }
        return null;
    }

    /**
     * 根据id更新培训计划
     * @param record
     * @param uploadFiles 需要上传的文件
     * @param deletedFiles 需要删除的文件
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int updateByPrimaryKeySelective(TrainingPlan record,String uploadFiles,String deletedFiles,String empIds) {
        // 数据保存成功之后，返回的条数
        int resultCount = 0;
        // 判断数据是否为空
        if(null == record){
            return  resultCount;
        }
        // 更新培训计划信息
        resultCount +=   planMapper.updateByPrimaryKeySelective(record);
        // 保存附件
        resultCount += iamFileService.newInsertFile(uploadFiles,deletedFiles,record.getTrainingId());

        TrainingPeople trainingPeople= new TrainingPeople();
        if(StringUtils.isBlank(empIds)){
            // 删除已经存在的培训人员
            peopleService.delByTrainPlanId(record.getTrainingId());
            return resultCount;
        }
        // 培训人员数组
        String[] ids = empIds.split(",");

        // 根据培训计划id查询培训人员
        List<TrainingPeople> peoplesList =  peopleService.queryPeoPleByTrainingId(record.getTrainingId());
        // 新增以及以前都存在的
        List<TrainingPeople> oldAndNewPeople = new ArrayList<>();
        // 若没有人 则直接新增
        if(peoplesList == null || peoplesList.size()==0){
            // 设置创建者id
            trainingPeople.setCreatorId(record.getModifierId());
            // 设置培训计划id
            trainingPeople.setTrainingId(record.getTrainingId());
            for(String s :ids){
                // 设置唯一id
                trainingPeople.setTrainingPeopleId(UniqueUtil.uuid());
                // 设置培训人员id
                trainingPeople.setOperatorId(s);
                // 设置创建时间
                trainingPeople.setCreateTime(new Date());
                trainingPeople.setStatus(Short.parseShort("0"));
                resultCount += peopleService.insertSelective(trainingPeople);
            }
        }else{
            // 区分成员
            for(String s :ids){
                TrainingPeople people =null;
                for(int i=0; i<peoplesList.size();i++){
                       if(s.equals(peoplesList.get(i).getOperatorId())){
                           people=peoplesList.get(i);
                           break;
                       }
                }
                // 依旧存在的不变
                if(people != null){
                    oldAndNewPeople.add(people);
                // 新增的
                }else{
                    people = new TrainingPeople();
                    // 设置唯一id
                    people.setTrainingPeopleId(UniqueUtil.uuid());
                    // 设置培训人员id
                    people.setOperatorId(s);
                    // 设置创建时间
                    people.setCreateTime(new Date());
                    // 设置创建者id
                    people.setCreatorId(record.getModifierId());
                    // 设置培训计划id
                    people.setTrainingId(record.getTrainingId());
                    people.setModifierId(record.getModifierId());
                    people.setModifyTime(new Date());
                    people.setStatus(Short.parseShort("0"));
                    oldAndNewPeople.add(people);
                    // 插入新增的人员
                    resultCount += peopleService.insertSelective(people);
                }
            }

            // 删除不在范围中的 not in
            if(oldAndNewPeople.size()>0){
                peopleService.batchDel(oldAndNewPeople);
            }
        }

        return  resultCount;
    }

    /**
     * 培训计划列表查询
     * @param trainingPlan
     * @return
     */
    @Override
    public JSONObject list(TrainingPlan trainingPlan) {
        JSONObject jsonObject = new JSONObject();
        // 分页设置
        trainingPlan.setLimit( trainingPlan.getLimit() == null ? Integer.valueOf(10) : trainingPlan.getLimit() );
        trainingPlan.setOffset( trainingPlan.getOffset() == null ? Integer.valueOf(0) : trainingPlan.getOffset() );
        // 总条数
        jsonObject.put("total",planMapper.queryCount(trainingPlan));
        List<TrainingPlan> trainList = planMapper.queryList(trainingPlan);
        jsonObject.put("rows", JSON.toJSON(trainList));
        return jsonObject;
    }

    /**
     * 判断培训计划名是否存在
     * @param planName 名称
     * @return  true:存在 false:不存在
     */
    @Override
    public boolean isExitByName(String planName){
        return planMapper.isExitByName( planName) >0 ? true : false;
    }

    /**
     * 根据名字查询培训计划
     * @param planName
     * @return
     */
    @Override
    public List<TrainingPlan> searchByName(String planName){
        Map<String,Object> searchMap = new HashMap<>();
        searchMap.put("planName",planName);
        List<TrainingPlan> trainingPlanList = planMapper.searchByName(searchMap);
        return trainingPlanList;
    }
    /**
     * 启用/不启用培训计划
     * @param plan
     * @return
     */
    @Override
    public int startOrStop(TrainingPlan plan){
        return planMapper.startOrStop(plan);
    }
}
